package structure;

import java.util.Arrays;

public class MyArrayList1 {
    private static final int DEFAULT_CAPACITY = 10;
    private int[] elem;
    private int size; // 顺序表中有效数据个数

    public MyArrayList1() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    public boolean isFull() {
        return size == elem.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(int data) {
        if (isFull()) {
            grow();
        }
        elem[size++] = data;
    }

    private void grow() {
        this.elem = Arrays.copyOf(elem, elem.length * 2);
    }

    public void add(int data, int index) {
        if (index < 0 || index > size) {
            return;
        }
        if (isFull()) {
            grow();
        }
        // 拿到最后一个元素的下标
        int last = size - 1;
        // 把在 >= index 的元素, 向后移动, 给新插入的元素腾出位置
        while (last >= index) {
            elem[last+1] = elem[last];
            last--;
        }
        elem[index] = data;
        size++;
    }

    public int indexOf(int data) {
        for (int i = 0; i < size; i++) {
            if (elem[i] == data) {
                return i;
            }
        }
        return -1;
    }

    public boolean contains(int data) {
        return indexOf(data) != -1;
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        return elem[index];
    }

    public int remove(int data) {
        // 找到该元素的下标
        int index = indexOf(data);
        if (index == -1) {
            return -1;
        }
        int removeElem = elem[index];
        // 让后面的元素向前移动一位
        for (int i = index; i < size - 1; i++) {
            elem[i] = elem[i+1];
        }
        size--;
        return removeElem;
    }

    public boolean removeAll(int data) {
        int index = indexOf(data);
        if (index == -1) {
            // 没找到返回false
            return false;
        }

        // 找到了
        while (index != -1) {
            for (int i = index; i < size - 1; i++) {
                elem[i] = elem[i+1];
            }
            size--;
            index = indexOf(data);
        }
        return true;
    }

    public void set(int data, int index) {
        if (index < 0 || index >= size) {
            return;
        }
        elem[index] = data;
    }

    public int size() {
        return size;
    }

    public void clear() {
//        size = 0;
        for (int i = 0; i < size; i++) {
//            elem[i] = null;
        }
        size = 0;
    }
}
